<?php
namespace app\api\controller;

class Vehicle extends Permission
{
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = $this->_listMap();


        $total = db('Vehicle')->where($map)->count();

        $rows = db('Vehicle')->order('id', 'desc')->page($page,$limit)->where($map)->select();

        $profitTarget = $this->_getProfit();

        $list = [];

        foreach ($rows as $v) {
            $time = time() - strtotime($v['reg_date']);
            $v['age'] = ceil($time / 31536000);
            $v['profitTarget'] = isset($profitTarget[$v['age']]) ? $profitTarget[$v['age']] : 0;
            if($v['reg_date'] == '0000-00-00') $v['reg_date'] = '';
            if($v['business_date'] == '0000-00-00') $v['business_date'] = '';
            if($v['check_date'] == '0000-00-00') $v['check_date'] = '';
            if($v['insurance_date_b'] == '0000-00-00') $v['insurance_date_b'] = '无数据';
            if($v['insurance_date_c'] == '0000-00-00') $v['insurance_date_c'] = '无数据';
            if($v['contract_end'] == '0000-00-00') $v['contract_end'] = '';
            if($v['contract_start'] == '0000-00-00') $v['contract_start'] = '';
            $v['statusType'] = $this->_getVehicleStatusType($v);
            $v['insurance_date_c_out'] = strtotime($v['insurance_date_c']) > time() ? 0 : 1;
            $v['insurance_date_b_out'] = strtotime($v['insurance_date_b']) > time() ? 0 : 1;
            $v['profit'] = formatMoneyShow($v['profit']);
            $v = $this->_formatImages($v);
            $v['bDay'] = timeToDay(strtotime($v['insurance_date_b']));
            $v['cDay'] = timeToDay(strtotime($v['insurance_date_c']));

            $list[] = $v;
        }

        
        $data = [
            'total' => $total,
            'list' => $list,
            'map' => $map
        ];

        $this->resSuc($data);
    }

    private function _getProfit()
    {
        $data = [];
        $rows = db('ProfitTarget')->select();
        foreach ($rows as $v) {
            $data[$v['age']] = formatMoneyShow($v['amount']);
        }
        return $data;
    }
    private function _formatImages($v)
    {
        // 行驶证
        if($v['xsz'])
        {
            $tmp = json_decode($v['xsz'],true);
            $img = [];
            if($tmp[0] != '')
            {
                foreach ($tmp as $i) {
                    $img[]['url'] = $i;
                }
            }
            $v['xszImg'] = $img;
        }
        else
        {
            $v['xszImg'] = [];
        } 
        // 身份证
        if($v['sfz'])
        {
            $tmp = json_decode($v['sfz'],true);
            $img = [];
            if($tmp[0] != '')
            {
                foreach ($tmp as $i) {
                    $img[]['url'] = $i;
                }
            }
            $v['sfzImg'] = $img;
        }
        else
        {
            $v['sfzImg'] = [];
        } 
        // 从业资格证
        if($v['cyzgz'])
        {
            $tmp = json_decode($v['cyzgz'],true);
            $img = [];
            if($tmp[0] != '')
            {
                foreach ($tmp as $i) {
                    $img[]['url'] = $i;
                }
            }
            $v['cyzgzImg'] = $img;
        }
        else
        {
            $v['cyzgzImg'] = [];
        } 
        // 驾驶证
        if($v['jsz'])
        {
            $tmp = json_decode($v['jsz'],true);
            $img = [];
            if($tmp[0] != '')
            {
                foreach ($tmp as $i) {
                    $img[]['url'] = $i;
                }
            }
            $v['jszImg'] = $img;
        }
        else
        {
            $v['jszImg'] = [];
        } 
        // 其他
        if($v['qtz'])
        {
            $tmp = json_decode($v['qtz'],true);
            $img = [];
            if($tmp[0] != '')
            {
                foreach ($tmp as $i) {
                    $img[]['url'] = $i;
                }
            }
            $v['qtzImg'] = $img;
        }
        else
        {
            $v['qtzImg'] = [];
        }
        return $v;
    }

    public function _getVehicleStatusType($v)
    {
        switch ($v['status']) {
            case '正常':
                return 'success';
                break;
            case '转出':
                return 'danger';
                break;
            case '失联':
                return 'warning';
                break;
            
            default:
                return '';
                break;
        }
    }

    # 即将过期
    public function getEndList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = $this->_listMap();

        $currentDate = date('Y-m-d',strtotime('+1 days'));
        $futureDate = date('Y-m-d', strtotime('+30 days'));

        $order = '';
        if($this->input_data['deadlineType'] == '交强险')
        {
            $order = 'insurance_date_c ASC';
            $map['insurance_date_c'] = ['BETWEEN',[$currentDate,$futureDate]];
        }
        if($this->input_data['deadlineType'] == '商业险')
        {
            $order = 'insurance_date_b ASC';
            $map['insurance_date_b'] = ['BETWEEN',[$currentDate,$futureDate]];
        }

        $total = db('Vehicle')->where($map)->count();

        $rows = db('Vehicle')->order('insurance_date_c', 'ASC')->page($page,$limit)->where($map)->select();


        $list = [];

        foreach ($rows as $v) {
            $v['bDay'] = timeToDay(strtotime($v['insurance_date_b']));
            $v['cDay'] = timeToDay(strtotime($v['insurance_date_c']));
            $list[] = $v;
        }

        
        $data = [
            'total' => $total,
            'list' => $list,
            'map' => $map
        ];

        $this->resSuc($data);
    }
    # 导出过期车辆
    public function exportinTheEnd()
    {
        $map = $this->_listMap();

        $currentDate = date('Y-m-d');

        $currentDate = date('Y-m-d',strtotime('+1 days'));
        $futureDate = date('Y-m-d', strtotime('+30 days'));

        $order = '';
        if($this->input_data['deadlineType'] == '交强险')
        {
            $order = 'insurance_date_c ASC';
            $map['insurance_date_c'] = ['BETWEEN',[$currentDate,$futureDate]];
        }
        if($this->input_data['deadlineType'] == '商业险')
        {
            $order = 'insurance_date_b ASC';
            $map['insurance_date_b'] = ['BETWEEN',[$currentDate,$futureDate]];
        }

        $list = db('Vehicle')->order($order)->where($map)->select();


        $data = [
            'list' => $list,
            'type' => 'vehicleInTheEnd'
        ];
        $excelName = action('common/PhpOffice/exportExcel',$data);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$excelName;

        $this->resSuc($url);

        $this->resSuc($data);
    }

    public function getExpiredList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = $this->_listMap();

        $currentDate = date('Y-m-d');

        
        $order = '';
        if($this->input_data['deadlineType'] == '交强险')
        {
            $order = 'insurance_date_c ASC';
            $map['insurance_date_c'] = ['<',$currentDate];
        }
        if($this->input_data['deadlineType'] == '商业险')
        {
            $order = 'insurance_date_b ASC';
            $map['insurance_date_b'] = ['<',$currentDate];
        } 

        

        $total = db('Vehicle')->where($map)->count();

        $rows = db('Vehicle')->order($order)->page($page,$limit)->where($map)->select();


        $list = [];

        foreach ($rows as $v) {
            $list[] = $v;
        }

        
        $data = [
            'total' => $total,
            'list' => $list,
            'map' => $map
        ];

        $this->resSuc($data);
    }
    # 导出过期车辆
    public function exportExpired()
    {
        $map = $this->_listMap();

        $currentDate = date('Y-m-d');

        $order = '';
        if($this->input_data['deadlineType'] == '交强险')
        {
            $order = 'insurance_date_c ASC';
            $map['insurance_date_c'] = ['<',$currentDate];
        }
        if($this->input_data['deadlineType'] == '商业险')
        {
            $order = 'insurance_date_b ASC';
            $map['insurance_date_b'] = ['<',$currentDate];
        }
        


        $list = db('Vehicle')->order($order)->where($map)->select();


        $data = [
            'list' => $list,
            'type' => 'vehicleExpired'
        ];
        $excelName = action('common/PhpOffice/exportExcel',$data);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$excelName;

        $this->resSuc($url);

        $this->resSuc($data);
    }

    public function update()
    {
        $data = [];
        
        $company = db('Company')->where(['id'=>$this->input_data['company_id']])->find();
        $data['area_id'] = $company['area_id'];
        $data['area'] = $company['area'];
        $data['company'] = $company['title'];
        $data['company_id'] = $company['id'];

        $data['plate_number'] = $this->input_data['plate_number'];
        $data['tel'] = $this->input_data['tel'];
        $data['realname'] = $this->input_data['realname'];
        $data['idcard'] = $this->input_data['idcard'];
        $data['address'] = $this->input_data['address'];
        $data['brand'] = $this->input_data['brand'];
        $data['vehicle_type'] = $this->input_data['vehicle_type'];
        $data['vehicle_report_type'] = $this->input_data['vehicle_report_type'];
        $data['vehicle_model'] = $this->input_data['vehicle_model'];
        $data['drive_type'] = $this->input_data['drive_type'];
        $data['color'] = $this->input_data['color'];
        $data['vin_number'] = $this->input_data['vin_number'];
        $data['engine_number'] = $this->input_data['engine_number'];
        $data['business_cert'] = $this->input_data['business_cert'];
        $data['reg_date'] = $this->input_data['reg_date'];
        $data['check_date'] = $this->input_data['check_date'];
        $data['business_date'] = $this->input_data['business_date'];
        $data['insurance_date_c'] = $this->input_data['insurance_date_c'];
        $data['insurance_date_b'] = $this->input_data['insurance_date_b'];
        $data['weight'] = $this->input_data['weight'];
        $data['full_weight'] = $this->input_data['full_weight'];
        $data['approved_weight'] = $this->input_data['approved_weight'];
        $data['passenger'] = $this->input_data['passenger'];
        $data['engine_model'] = $this->input_data['engine_model'];
        $data['fuel_type'] = $this->input_data['fuel_type'];
        $data['engine_power'] = $this->input_data['engine_power'];
        $data['manufacturer'] = $this->input_data['manufacturer'];
        $data['wheel_track'] = $this->input_data['wheel_track'];
        $data['wheel_number'] = $this->input_data['wheel_number'];
        $data['wheel_size'] = $this->input_data['wheel_size'];
        $data['wheel_base'] = $this->input_data['wheel_base'];
        $data['outline_size'] = $this->input_data['outline_size'];
        $data['cargo_size'] = $this->input_data['cargo_size'];
        $data['status'] = $this->input_data['status'];
        $data['contract_start'] = $this->input_data['contract_start'];
        $data['contract_end'] = $this->input_data['contract_end'];
        $data['invoice_value'] = $this->input_data['invoice_value'];
        $data['gps'] = $this->input_data['gps'];
        $data['remark'] = $this->input_data['remark'];
        $data['buy_price'] = $this->input_data['buy_price'];
        $data['buy_agent_fee'] = $this->input_data['buy_agent_fee'];
        $data['buy_other_fee'] = $this->input_data['buy_other_fee'];
        $data['buy_images'] = $this->input_data['buy_images'];



        if($this->input_data['id'] > 0)
        {
            db('Vehicle')->where(['id'=>$this->input_data['id']])->update($data);
        }
        else
        {
            $map = [
                'vin_number' => $this->input_data['vin_number'],
                'plate_number' => $this->input_data['plate_number'],
            ];

            if(db('Vehicle')->where($map)->find()) $this->resErr('该车辆已存在，不能重复添加');
            $id = db('Vehicle')->insertGetId($data);
        }

        $this->resSuc('ok');
    }

    public function del()
    {
        db('Vehicle')->delete( $this->input_data['id'] );
        
        $this->resSuc('ok');
    }

    public function exportExcel()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = $this->_listMap();

        $total = db('Vehicle')->where($map)->count();

        $rows = db('Vehicle')->order('id', 'desc')->page($page,$limit)->where($map)->select();


        $list = [];

        foreach ($rows as $v) {
            if($v['reg_date'] == '0000-00-00') $v['reg_date'] = '';
            if($v['business_date'] == '0000-00-00') $v['business_date'] = '';
            if($v['check_date'] == '0000-00-00') $v['check_date'] = '';
            if($v['insurance_date_b'] == '0000-00-00') $v['insurance_date_b'] = '';
            if($v['insurance_date_c'] == '0000-00-00') $v['insurance_date_c'] = '';
            if($v['contract_end'] == '0000-00-00') $v['contract_end'] = '';
            if($v['contract_start'] == '0000-00-00') $v['contract_start'] = '';
            $list[] = $v;
        }

        $data = [
            'list' => $list,
            'type' => 'VehicleList'
        ];

        $result = action('common/PhpOffice/exportExcel',$data);

        $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$result;

        $this->resSuc($url);
    }

    public function importExcel()
    {
        $data = [
            'url' => $this->input_data['url']
        ];

        $result = action('common/PhpOffice/getExcelDetail',$data);
        $batid = time();
        $errList = [];
        foreach ($result as $k => $v) {

            $row = $k + 1;
            

            $res = $this->_insertVehicle($v);
            if($res !== true)
            {
                $errList[] = '第'.$row.'行数据有误：'.$res;
            }

        }

        $this->resSuc($errList);
    }

    private function _verifyRepeat($vin_number,$plate_number)
    {
        $map = [
            'plate_number' => $plate_number
        ];
        if(db('Vehicle')->where($map)->find()) return '车牌号'.$plate_number.'的车辆已存在系统中，无法重复添加';
        $map = [
            'vin_number' => $vin_number
        ];
        if(db('Vehicle')->where($map)->find()) return '车架号'.$vin_number.'的车辆已存在系统中，无法重复添加';

        return true;
    }

    private function _insertVehicle($v)
    {
        $repeat = $this->_verifyRepeat($v[14],$v[4]);
        if($repeat !== true) return $repeat;
        $company = $this->_getCompany($v[3]);
        if(!is_array($company)) return $company;

        // 去null
        $count = count($v);
        for ($i=0; $i < $count; $i++) { 
            if($v[$i] == null) $v[$i] == '';
        }

        $data = [
            'vin_number' => $v['14'] == null ? '' : $v['14'],
            'plate_number' => $v['4'] == null ? '' : $v['4'],
            'company_id' => $company['id'],
            'company' => $company['title'],
            'area' => $company['area'],
            'area_id' => $company['area_id'],
            'm_id' => $v['1'] == null ? '' : $v['1'],
            'realname' => $v['5'] == null ? '' : $v['5'],
            'idcard' => $v['6'] == null ? '' : $v['6'],
            'tel' => $v['7'] == null ? '' : $v['7'],
            'address' => $v['8'] == null ? '' : $v['8'],
            'brand' => $v['9'] == null ? '' : $v['9'], // 品牌
            'vehicle_type' => $v['10'] == null ? '' : $v['10'], // 车辆类型
            'vehicle_model' => $v['11'] == null ? '' : $v['11'], // 车辆型号
            'drive_type' => $v['12'] == null ? '' : $v['12'], // 驱动形式
            'color' => $v['13'] == null ? '' : $v['13'], // 车身颜色
            'vin_number' => $v['14'] == null ? '' : $v['14'], // 车架号
            'engine_number' => $v['15'] == null ? '' : $v['15'], // 发动机号
            'business_cert' => $v['16'] == null ? '' : $v['16'], // 营运证号
            'reg_date' => $v['17'] == null ? '0000-00-00' : date('Y-m-d',strtotime($v['17'])), // 登记日期
            'check_date' => $v['18'] == null ? '0000-00-00' : date('Y-m-d',strtotime($v['18'])), // 检验有效期
            'business_date' => $v['19'] == null ? '0000-00-00' : date('Y-m-d',strtotime($v['19'])), // 营运有效期
            'insurance_date_c' => $v['20'] == null ? '0000-00-00' : date('Y-m-d',strtotime($v['20'])), // 交强有效期
            'insurance_date_b' => $v['21'] == null ? '0000-00-00' : date('Y-m-d',strtotime($v['21'])), // 商业有效期
            'weight' => $v['22'] == null ? '' : $v['22'], // 总质量
            'full_weight' => $v['23'] == null ? '' : $v['23'], // 整备质量
            'approved_weight' => $v['24'] == null ? '' : $v['24'], // 核定质量
            'passenger' => $v['25'] == null ? '' : $v['25'], // 核定载客
            'engine_model' => $v['26'] == null ? '' : $v['26'], // 发动机型号
            'fuel_type' => $v['27'] == null ? '' : $v['27'], // 燃料种类
            'engine_power' => $v['28'] == null ? '' : $v['28'], // 排量功率
            'manufacturer' => $v['29'] == null ? '' : $v['29'], // 制造厂家
            'wheel_track' => $v['30'] == null ? '' : $v['30'], // 轮距
            'wheel_number' => $v['31'] == null ? '' : $v['31'], // 轮胎数
            'wheel_size' => $v['32'] == null ? '' : $v['32'], // 轮胎规格
            'wheel_base' => $v['33'] == null ? '' : $v['33'], // 轴距
            'outline_size' => $v['34'] == null ? '' : $v['34'], // 外廓尺寸
            'cargo_size' => $v['35'] == null ? '' : $v['35'], // 货箱尺寸
            'status' => $v['36'] == null ? '' : $v['36'], // 状态
            'contract_start' => $v['37'] == null ? '0000-00-00' : $v['37'], // 签合同日期
            'contract_end' => $v['38'] == null ? '0000-00-00' : $v['38'], // 合同到期
            'invoice_value' => $v['39'] == null ? '' : $v['39'], // 发票金额
            // 'manage_fee' => $v['40'] == null ? '' : $v['5'], // gps平台
            // 'manage_fee' => $v['41'] == null ? '' : $v['41'], // 管理费
            'remark' => $v['42'] == null ? '' : $v['42'], // 备注
            // 'id_card' => $v['43'], // 数量
            'vehicle_report_type' => $v['44'] == null ? '' : $v['44'], // 车辆统计类型
            // 'id_card' => $v['45'], // 统计车辆数
            // 'insurance_end_month' => $v['46'] == null ? '' : $v['46'], // 保险到期月份
            // 'id_card' => $v['47'] // 保险月份统计
       
        ];

        db('Vehicle')->insert($data);

        return true;
    }

    private function _getCompany($name)
    {
        $map = [
            'title' => $name
        ];
        if(!$com = db('Company')->where($map)->find())
        {
            return '车队不存在';
        }
        return $com;
    }


    //停用 启用
    public function updateStatus()
    {
        $st = [1,0];
        $user['id'] = $this->input_data['id'];
        $user['status'] = $st[$this->input_data['status']];

        
        db('OaVehicle')->update($user);

        $this->resSuc('ok');
    }

    private function _listMap(){
        $map = [];

        if($this->post('area_id') > 0)
        {
            $map['area_id'] = $this->post('area_id');
        }
        else
        {
            $map['area_id'] = ['IN',$this->myAllAreaIds];
        }

        if(isset($this->input_data['company']) && $this->input_data['company'] != '') $map['company'] = ['LIKE','%'.$this->input_data['company'].'%'];

        if(isset($this->input_data['plate_number']) && $this->input_data['plate_number'] !== '') $map['plate_number'] = ['LIKE','%'.$this->input_data['plate_number'].'%'];

        if(isset($this->input_data['status']) && $this->input_data['status'] !== '') $map['status'] = $this->input_data['status'];

        return $map;
    }

    public function export()
    {
        $map = $this->_listMap();


        $list = db('OaVehicle')->where($map)->order('id DESC')->select() ;

        $data = [
            'list' => $list,
            'type' => 'driver'
        ];
        $excelName = action('common/PhpOffice/exportExcel',$data);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$excelName;

        $this->resSuc($url);
    }

    // 买保险
    public function updateInsurance()
    {
        $deadline = $this->_getDeadline();
        $salesman = $this->_getSalesman();

        $status = 0;

        if($this->input_data['cash'] == 0)
        {
            $status = $this->input_data['pdf'] == '' ? 20 : 30;
        }
        else
        {
            $status = 10;
        }

        // price是10000元 rebate是百分比40 这里计算出来的价格单位是分
        $rebateAmount = $this->_getReabteAmount();

        $data = [
            'choose' => 1,
            'insurance_salesman' => $salesman['realname'],
            'insurance_salesman_id' => $salesman['id'],
            'vehicle_id' => $this->input_data['vehicle_id'],
            'cate' => $this->input_data['cate'],
            'status' => $status,
            'price' => formatMoneySave($this->input_data['price']),
            'raise_price' => formatMoneySave($this->input_data['raise_price']),
            'tax_price' => formatMoneySave($this->input_data['tax_price']),
            'rebate' => $this->input_data['rebate'],
            'insurance' => $this->input_data['insurance'],
            'insurance_id' => $this->input_data['insurance_company_id'],
            'rebate_amount' => $rebateAmount,
            'plan_id' => 0,
            'trade_id' => 0,
            'create_time' => time(),
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'images' => $this->input_data['images'],
            's_time' => $deadline['s_time'],
            'e_time' => $deadline['e_time'],
            'cash' => $this->input_data['cash'],
            'pdf' => $this->input_data['pdf'],
        ];
        
        $offerId = db('Insurance')->insertGetId($data);
        $data['id'] = $offerId;

        # 不是现结，并且上传了pdf
        # 更新车辆保险到期日期
        # 创建车辆收支
        if($this->input_data['cash'] == 0 && $this->input_data['pdf'] != '')
        {
            $this->_updateVehicleInsuranceDate($data);
            $this->_createVehicleInsuranceCost($data);
        }

        $this->resSuc('ok');
    }
    // 创建车辆买保险的收支
    private function _createVehicleInsuranceCost($insurance)
    {
        $data['io_type'] = '支出';
        $data['relation_type'] = '买保险';
        $data['relation_id'] = $insurance['id'];
        $data['images'] = '';
        $data['status'] = 20; // 已完成
        $data['pay_user'] = $this->user['realname'];
        $data['pay_user_id'] = $this->user['id'];
        $data['pay_time'] = time();

        $data['create_user'] = $this->user['realname'];
        $data['create_user_id'] = $this->user['id'];
        $data['create_time'] = time();

        $data['pay_record_id'] = '';
        $data['vehicle_id'] = $insurance['vehicle_id'];
        $data['amount'] = $insurance['price'];
        $data['cate'] = '保险购买';
        db('VehicleIncomeExpense')->insertGetId($data);

        $data['io_type'] = '收入';
        $data['amount'] = $insurance['rebate_amount'];
        $data['cate'] = '保险返点';
        db('VehicleIncomeExpense')->insertGetId($data);

        if($insurance['raise_price'] > 0)
        {
            $data['io_type'] = '收入';
            $data['amount'] = $insurance['raise_price'];
            $data['cate'] = '保险加价';
            db('VehicleIncomeExpense')->insertGetId($data);
        }

        # 更新车辆利润
        action('common/Vehicle/updateProfit',['vehicleId'=>$insurance['vehicle_id']]);

    }

    // 计算返点
    private function _getReabteAmount()
    {
        
        $rebateAmount = bcmul($this->input_data['price'], $this->input_data['rebate']);

        return $rebateAmount;
    }
    private function _updateVehicleInsuranceDate($data)
    {
        $map = [
            'id' => $data['vehicle_id']
        ];

        $uData = [];
        if($data['cate'] == '交强险') $uData['insurance_date_c'] = date('Y-m-d',$data['e_time']);
        if($data['cate'] == '商业险') $uData['insurance_date_b'] = date('Y-m-d',$data['e_time']);

        db('Vehicle')->where($map)->update($uData);
    }
    private function _getDeadline()
    {
        $sh = $this->input_data['s_time_h'] ? $this->input_data['s_time_h'] : 0;
        // $eh = $this->input_data['e_time_h'] ? $this->input_data['e_time_h'] : 0;
        $eh = 0;
        $si = $this->input_data['s_time_i'] ? $this->input_data['s_time_i'] : 0;
        // $ei = $this->input_data['e_time_i'] ? $this->input_data['e_time_i'] : 0;
        $ei = 0;


        $s = $this->input_data['s_time_date'].' '.$sh.':'.$ei.':00';
        $e = $this->input_data['e_time_date'].' '.$eh.':'.$ei.':00';

        $data = [
            's_time' => strtotime($s),
            'e_time' => strtotime($e),
        ];
        return $data;
    }
    private function _getSalesman()
    {
        # 逻辑
        # 业务员id为零 表示直接填写，新建并保存业务员
        $salesman = [
            'id' => $this->input_data['salesman_id'],
            'realname' => $this->input_data['salesman']
        ];

        if($this->input_data['salesman_id'] == 0)
        {
            $data = [
                'insurance_company_id' => $this->input_data['insurance_company_id'],
                'realname' => $this->input_data['salesman']
            ];
            # 先判断提交的业务员名字是否存在，不存在才添加
            if($sales = db('InsuranceCompanySalesman')->where($data)->find())
            {
                $salesman['id'] = $sales['id'];
            }
            else
            {
                $sId = db('InsuranceCompanySalesman')->insertGetId($data);
                $salesman['id'] = $sId;
            }
        }
        return $salesman;
    }

    public function updateImages()
    {
        $map = [
            'id' => $this->input_data['id']
        ];
        $data = [
            'xsz' => $this->input_data['xsz'],
            'sfz' => $this->input_data['sfz'],
            'cyzgz' => $this->input_data['cyzgz'],
            'jsz' => $this->input_data['jsz'],
            'qtz' => $this->input_data['qtz']
        ];
        db('Vehicle')->where($map)->update($data);

        // 保存历史图片
        $v = db('Vehicle')->where($map)->find();
        $data = [
            'xsz_all' => $v['xsz_all'].$this->input_data['xsz'],
            'sfz_all' => $v['sfz_all'].$this->input_data['sfz'],
            'jsz_all' => $v['jsz_all'].$this->input_data['jsz'],
            'cyzgz_all' => $v['cyzgz_all'].$this->input_data['cyzgz'],
            'qtz_all' => $v['qtz_all'].$this->input_data['qtz'],
        ];
        db('Vehicle')->where($map)->update($data);

        $this->resSuc('ok');
    }

    public function getById()
    {
        $map = [
            'id' => $this->input_data['id']
        ];

        $data = db('Vehicle')->where($map)->find();
        $this->resSuc($data);
    }

    // 车辆档案
    public function getFilesById()
    {
        $vehicleId = $this->input_data['id'];
        # 成本 车辆收购价
        $vehicle = db('Vehicle')->where(['id'=>$vehicleId])->find(); 
        $cost = $vehicle['buy_price'] + $vehicle['buy_agent_fee'] + $vehicle['buy_other_fee'];
        # 利润 = 车辆收入 - 车辆购买成本
        $income = $this->_getIncome($vehicleId);
        $profit = $income - $cost;

        # 欠款
        $bill = $this->_getBill($vehicleId);

        # 官司

        # gps费是否交清
        $gps = $this->_getGps($vehicleId);

        # 学习费
        $xx = $this->_getXx($vehicleId);

        # 二保情况
        $eb = $this->_getEb($vehicleId);

        $data = [
            'profit' => $profit,
            'bill' => $bill,
            'xx' => $xx,
            'gps' => $gps,
            'eb' => $eb
        ];

        $this->resSuc($data);
    }

    private function _getGps($id)
    {
        $map = [
            'status' => 20,
            'cate' => 'GPS费',
            'io_type' => '收入',
            'vehicle_id' => $id
        ];
        if( $data = db('VehicleIncomeExpense')->where($map)->order('id DESC')->find() )
        {
            return '最后一次在'.date('Y-m-d',$data['create_time']).'缴费'.formatMoneyShow($data['amount']);
        }
        else
        {
            return '未收过GPS费';
        }

         
    }
    private function _getXx($id)
    {
        $map = [
            'status' => 20,
            'cate' => '学习费',
            'io_type' => '收入',
            'vehicle_id' => $id
        ];
        if( $data = db('VehicleIncomeExpense')->where($map)->order('id DESC')->find() )
        {
            return '最后一次在'.date('Y-m-d',$data['create_time']).'缴费'.formatMoneyShow($data['amount']);
        }
        else
        {
            return '未收过学习费';
        }
    }
    private function _getEb($id)
    {
        $map = [
            'status' => 20,
            'cate' => '二保费',
            'io_type' => '收入',
            'vehicle_id' => $id
        ];
        if( $data = db('VehicleIncomeExpense')->where($map)->order('id DESC')->find() )
        {
            return '最后一次在'.date('Y-m-d',$data['create_time']).'缴费'.formatMoneyShow($data['amount']);
        }
        else
        {
            return '未收过二保费';
        }
    }



    private function _getBill($id)
    {
        $map = [
            'vehicle_id' => $id,
            'repay_status' => 0, // 未还清
        ];
        $rows = db('Bill')->where($map)->select();
        $amount = 0;
        foreach ($rows as $v) {
            $amount += bcadd($v['amount'], $v['interest']);
            $amount -= $v['repay_total'];
        }
        return $amount;
    }

    // 获取车辆收入
    private function _getIncome($id)
    {
        $map = [
            'vehicle_id' => $id,
            'status' => 20
        ];
        $rows = db('VehicleIncomeExpense')->where($map)->select();
        $cost = 0;
        foreach ($rows as $v) {
            $cost += $v['io_type'] == '收入' ? $v['amount'] : $v['amount'] * -1;
        }

        return formatMoneyShow($cost);
    }

}
